import './index.less'
import { Button } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import createEvent, { useT, request, goTo } from '@designable/event-system'
import { Modal, message } from 'antd'
import { ActionType } from '@ant-design/pro-table'
import { useRef } from 'react'
import { FormConsumer } from '@formily/react'
import React, { useState } from 'react'
import EditableProTable from '@ant-design/pro-table'
import { useForm } from '@formily/react'
import { useField } from '@formily/react'
import { observer } from '@formily/reactive-react'

type PropsType = {
  confirmExpression: string
}

export function exchangeGeneralContents(params?: object) {
  return request({
    uri: '/api/tenant/exchange/general/contents',
    params,
    method: 'POST',
  })
}

function Com(props: PropsType) {
  const { confirmExpression } = props
  const actionRef = useRef<ActionType>()
  const [open, setOpen] = useState(false)
  const $t = useT()
  const [selectRow, setSelectRow] = useState<any>({ relationCode: null })
  const form = useForm() as any
  const field = useField() as any
  const disabled = (field.pattern || field.props.pattern) === 'disabled'

  const columns: any[] = [
    {
      title: $t('权益ID'),
      dataIndex: 'relationCode',
      search: false,
    },
    {
      title: $t('权益名称'),
      dataIndex: 'relationName',
    },
    {
      title: $t('权益类型'),
      dataIndex: 'relationTypeName',
      ellipsis: true,
      search: false,
    },
    {
      title: $t('有效期'),
      dataIndex: 'equityExpirationDesc',
      ellipsis: true,
      search: false,
    },
  ]

  return (
    <>
      <div className={'categoryWrap'}>
        <FormConsumer>
          {(form) => {
            const { equityGetResp } = form.getFormState().values
            return (
              <>
                <div className={'tableWrap'}>
                  <div className={'label'}>
                    {[
                      $t('权益编号'),
                      $t('权益名称'),
                      $t('权益类型'),
                      $t('权益状态'),
                      $t('操作'),
                    ].map((item: any, index: number) => (
                      <div key={index}>{item}</div>
                    ))}
                  </div>
                  {equityGetResp && (
                    <div className={'value'}>
                      {[
                        equityGetResp.relationCode || equityGetResp.equityCode,
                        equityGetResp.relationName || equityGetResp.equityName,
                        equityGetResp.relationTypeName ||
                          equityGetResp.categoryTypeName,
                        equityGetResp.statusName ||
                          equityGetResp.equityStatusName,
                        disabled ? (
                          <Button
                            type="link"
                            onClick={() => {
                              const id =
                                equityGetResp.relationId || equityGetResp.id
                              goTo(`/equity/equityMgmt/handle/edit?id=${id}`)
                            }}
                          >
                            {$t('查看')}
                          </Button>
                        ) : (
                          <Button type="link" onClick={() => setOpen(true)}>
                            {$t('更换')}
                          </Button>
                        ),
                      ].map((item: any, index: number) => (
                        <div key={index}>{item}</div>
                      ))}
                    </div>
                  )}
                </div>
                {!equityGetResp && (
                  <Button
                    icon={<PlusOutlined />}
                    block
                    onClick={() => {
                      if (!form.values.customerCode) {
                        message.error($t('请先选择客户'))
                        return
                      }
                      setOpen(true)
                    }}
                  >
                    {$t('选择权益')}
                  </Button>
                )}
              </>
            )
          }}
        </FormConsumer>
      </div>
      <Modal
        title={$t('选择权益')}
        width={1200}
        open={open}
        destroyOnClose
        onOk={async () => {
          if (!selectRow.relationCode) {
            message.error($t('请选择'))
            return
          }
          try {
            if (confirmExpression) {
              await createEvent(confirmExpression as string, {
                form,
                value: { ...selectRow },
                $t,
              })
            }
            setOpen(false)
          } catch (e) {
            // eslint-disable-next-line no-console
            console.error('执行确认表达式失败:', e)
          }
        }}
        onCancel={() => {
          setOpen(false)
        }}
        getContainer={() => {
          return (
            document.getElementById('designable-page-wrap') || document.body
          )
        }}
      >
        <EditableProTable
          columns={columns}
          actionRef={actionRef}
          tableAlertRender={false}
          rowSelection={{
            type: 'radio',
            defaultSelectedRowKeys: selectRow.relationCode
              ? [selectRow.relationCode]
              : [],
            onChange: (keys, rows) => {
              setSelectRow(rows[0])
            },
          }}
          request={async ({ relationName, ...params }) => {
            const { customerCode, agreementCode } = form.getFormState().values
            const res = await exchangeGeneralContents({
              ...params,
              name: relationName,
              channel: 'equityProduct',
              subCusCode: customerCode,
              agreementCode: agreementCode,
            })
            return {
              data: res['equities'],
              success: true,
              total: res['equities'].length,
            }
          }}
          rowKey="relationCode"
          pagination={{
            size: 'default',
            defaultPageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          search={{
            labelWidth: 'auto',
            collapsed: false,
            collapseRender: () => <></>,
            style: {
              background: '#F7F8FA',
              padding: '24px 20px',
              borderRadius: 4,
            },
          }}
          dateFormatter="string"
          toolBarRender={false}
        />
      </Modal>
    </>
  )
}

export const SelectEquity = observer(Com)
